package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.entity.merchant.InvestmentDetailEntity;
import com.sgb.link.service.MapService;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.router.PathUser;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityInvestmentApplyBinding;
import com.sgb.merchant.viewmodel.InvestmentApplyViewModel;
import com.swgk.core.base.model.entity.RouterKey;

import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.yalantis.ucrop.util.FileUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 王彬臣
 * @date: 2021/8/25
 * @Description: 投资项目报名提交页
 */
@Route(path = PathMerchant.InvestmentApplyActivity)
public class InvestmentApplyActivity extends BaseActivity<InvestmentApplyViewModel, MerchantActivityInvestmentApplyBinding> {
    @Autowired(name = RouterKey.DATA, desc = "详情信息")
    InvestmentDetailEntity entity;

    @Autowired(name = PathUser.AMapDialog)
    MapService mapService;
    // 打开文件管理器
    public static final int REQUESTCODE_OPEN_FILECHOOSER = 102;

    String linkName, linkPhone, money, address, fileName;

    boolean hasContent;//是否有填写类型
    private String filePath;
    private String fileSize, fileType;
    String applyNo;

    Map<String,Object> map=new HashMap<>();

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState, @Nullable @org.jetbrains.annotations.Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
      //  getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_investment_apply;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(InvestmentApplyViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.includeTitle.titleView.setText("我要报名");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            getEditContent();
            if (hasContent) {//有填写类提示用户
                showHintDialog();
                return;
            }
            finish();
        });
        mBinding.setClick(this);
        mBinding.itvMoney.setInfilterType(ItemInputTextView.TYPE_NUMBER_DECIMAL);
        mBinding.itvMoney.setCheck(10, 2, false);
        mBinding.itvMoney.setLabelRightMargin();
        if (entity != null) {
            mBinding.tvProjectName.setText(TextUtils.isEmpty(entity.getItemName())?"/":entity.getItemName());
            mBinding.tvName.setText(TextUtils.isEmpty(entity.getCompanyName())?"/":entity.getCompanyName());
            mBinding.tvType.setText(TextUtils.isEmpty(entity.getIndustryName())?"/":entity.getIndustryName());
            mBinding.tvProType.setText(TextUtils.isEmpty(entity.getItemTypeName()) ? "/" : entity.getItemTypeName());
            mBinding.tvPerson.setText(TextUtils.isEmpty(entity.getLinkName())?"/":entity.getLinkName());
            mBinding.tvPhone.setText(TextUtils.isEmpty(entity.getLinkPhone())?"/":entity.getLinkPhone());
            mBinding.tvMoney.setText(TextUtils.isEmpty(entity.getItemMoney())?"/":entity.getItemMoney()+"元");
            mBinding.tvAdress.setText(entity.getProviceName() + entity.getCityName() + entity.getRegionName() + entity.getAddressInfo());
            mBinding.stageName.setText(TextUtils.isEmpty(entity.getStageName())?"/":entity.getStageName());
            mBinding.tvSize.setText(TextUtils.isEmpty(entity.getCapacityScale())?"/":entity.getCapacityScale());
        }
        String company = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME, "");
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        String name = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "");
        if (type == 0) {
            mBinding.itvName.setContent(name);
        } else {
            mBinding.itvName.setContent(company);
        }

        mViewModel.ldUrl.observe(this,url->{
            map.put("fileName",fileName);
            map.put("fileUrl",url);
            mViewModel.addApply(map);
        });
        mViewModel.ldNo.observe(this,no->{
            applyNo=no;
            new RoundDialog.Builder(this)
                    .title("温馨提示")
                    .content("您的报名已经提交成功")
                    .cancel("查看我的报名")
                    .confirm("继续浏览")
                    .cancelable(false)
                    .cancelCallback(v->{
                        ActivityJump.startActivity(PathMerchant.ApplyDetailActivity, Pair.create(RouterKey.ID,applyNo));
                        setResult(200);
                        finish();
                    })
                    .confirmCallback(v12 -> {
                        setResult(RESULT_OK);
                        finish();
                    }).show();
        });
    }

    private void getEditContent() {
        linkName = mBinding.itvPerson.getContent();
        linkPhone = mBinding.itvPhone.getContent();
        money = mBinding.itvMoney.getContent();
        address = mBinding.itvAddress.getText().toString();
        if (!TextUtils.isEmpty(linkName) || !TextUtils.isEmpty(linkPhone)
                || !TextUtils.isEmpty(money) || !TextUtils.isEmpty(address) || !TextUtils.isEmpty(fileName)) {
            hasContent = true;
        } else {
            hasContent = false;
        }
    }

    //温馨提示
    private void showHintDialog() {
        new RoundDialog.Builder(this)
                .title("温馨提示")
                .content("此操作将丢失当前表单填写内容，\n" + "是否继续？")
                .cancel("取消")
                .confirm("确定")
                .cancelable(false)
                .confirmCallback(v12 -> finish()).show();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_commit) {
            if (!ClickUtils.isDoubleClick()) {
                getEditContent();
                if (TextUtils.isEmpty(linkName)) {
                    MToast.showToast(this, "请输入联系人!");
                    return;
                }
                if (TextUtils.isEmpty(linkPhone)) {
                    MToast.showToast(this, "请输入联系电话!");
                    return;
                } else if (!CheckUtils.isMobileForService(linkPhone.trim())) {
                    MToast.showToast(this, "请输入正确的电话格式！");
                    return;
                }
                if (TextUtils.isEmpty(money)) {
                    MToast.showToast(this, "请输入投资预算! ");
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    MToast.showToast(this, "请选择企业地址!");
                    return;
                }
                map.put("linkName", linkName);
                map.put("linkPhone", linkPhone);
                map.put("investmentBudget", money);
                map.put("itemNo", entity.getItemNo());
                DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
                if(!TextUtils.isEmpty(fileName)){
                    mViewModel.uploadFile(new File(filePath));
                }else{
                    mViewModel.addApply(map);
                }
            }

        } else if (v.getId() == R.id.iv_map) {
            if (entity != null) {
                ARouter.getInstance().build(PathUser.MapPositionActivity)
                        .withDouble("latitude", Double.valueOf(entity.getLat()))
                        .withDouble("longitude", Double.valueOf(entity.getLng()))
                        .withString("companyName", entity.getCompanyName())
                        .withString("address", entity.getProviceName() + entity.getCityName() + entity.getRegionName() + entity.getAddressInfo())
                        .navigation();

            }
        } else if (v.getId() == R.id.rl_address) {
            if (mapService != null)
                mapService.launchMap(this);
        } else if (v.getId() == R.id.tv_upload_annex) {
            if (!ClickUtils.isDoubleClick()) {
                Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
                fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
                //设置类型
                fileIntent.setType("application/zip|image/png|application/pdf|application/rar|image/jpeg");
                //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    fileIntent.putExtra(Intent.EXTRA_MIME_TYPES,
                            new String[]{"application/zip", "image/png", "application/pdf", "application/rar", "image/jpeg"});
                }
                startActivityForResult(fileIntent, REQUESTCODE_OPEN_FILECHOOSER);
            }
        } else if (v.getId() == R.id.tv_annex_delete) {

            if (!ClickUtils.isDoubleClick()) {
              /*  mAttachmentUrl = "";*/
                fileName = "";
                fileSize = "";
                fileType = "";
                mBinding.tvUploadAnnex.setVisibility(View.VISIBLE);
                mBinding.rlAnnexInfo.setVisibility(View.GONE);
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 2500) {
                AMapAddressEntity entity = get(data);
                if (entity == null) return;
                mBinding.itvAddress.setText(entity.getProvince() + entity.getCity() + entity.getDistrict() + entity.getSnippet());

                map.put("addressLat",entity.getLatitude());
                map.put("addressLng",entity.getLongitude());
                map.put("cityId",Integer.valueOf(entity.getCityNo()));
                map.put("proviceId",Integer.valueOf(entity.getProvinceNo()));
                map.put("regionId",Integer.valueOf(entity.getDistrictNo()));
                map.put("regionName",entity.getDistrictName());
                map.put("proviceName",entity.getProvinceName());
                map.put("cityName",entity.getCityName());
                map.put("addressInfo",entity.getProvinceName() + entity.getCityName() + entity.getDistrictName()+entity.getSnippet());

            } else if (requestCode == REQUESTCODE_OPEN_FILECHOOSER) {//选择文件返回
                if (data == null) {
                    LogUtil.d("TAG", "onActivityResult chooseFile data is null");
                    return;
                }
                handleFileChoose(data);
            }
        }
        if (requestCode == 255) {
            if (data == null) {
                return;
            }
        }
    }

    private void handleFileChoose(Intent data) {
        Uri uri = data.getData();
        /**
         * 得到uri对路径
         */
        if ("content".equalsIgnoreCase(uri.getScheme())||"file".equalsIgnoreCase(uri.getScheme())) {
            filePath = FileUtil.getFilePathForN(this,uri);
            fileName = new File(filePath).getName();
            String extension = FileUtil.getExtensionName(fileName);
            if (TextUtils.isEmpty(extension)) {
                MToast.showToast(this, "未获取到文件格式");
                return;
            }
            if (!extension.equals("pptx") && !extension.equals("ppt") && !extension.equals("pdf")
                    && !extension.equals("png") && !extension.equals("jpg") && !extension.equals("jpeg")
                    && !extension.equals("xls") && !extension.equals("xlsx") && !extension.equals("doc")
                    && !extension.equals("docx")) {
                MToast.showToast(this, "上传附件格式不正确！");
                return;
            }
            if (checkFileSize(filePath)) {
                mBinding.tvUploadAnnex.setVisibility(View.GONE);
                mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
                long fileLength = FileUtil.getFileLength(filePath);
                fileSize = FileUtil.formatFileSize(fileLength);
                fileType = FileUtil.getMimeType(new File(filePath));
                mBinding.tvAnnexName.setText(fileName);
                mBinding.tvAnnexSize.setText(fileSize);
                switch (fileType) {
                    case "image/jpg":
                    case "image/png":
                    case "image/jpeg":
                        Glide.with(this).load(R.mipmap.merchant_icon_img_type).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/msword":
                    case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                        Glide.with(this).load(R.mipmap.merchant_icon_doc).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/vnd.ms-powerpoint":
                    case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                        Glide.with(this).load(R.mipmap.merchant_icon_ppt).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/vnd.ms-excel":
                    case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                        Glide.with(this).load(R.mipmap.merchant_icon_xlsx).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/pdf":
                        Glide.with(this).load(R.mipmap.merchant_icon_pdf).into(mBinding.ivAnnexSimple);
                        break;
                }
            }
            return;
        }
        /***
         * //4.4以后
         */
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            filePath = FileUtils.getPath(this, uri);
        } else {//4.4以下下系统调用方法
            filePath = FileUtil.getRealPathFromURI(uri, this);
        }
        if(TextUtils.isEmpty(filePath)){
            MToast.showToast(this,"未找到文件路径");
            return;
        }
        fileName = new File(filePath).getName();
        String extension = FileUtil.getExtensionName(fileName);
        if (TextUtils.isEmpty(extension)) {
            MToast.showToast(this, "未获取到文件格式");
            return;
        }
        if (!extension.equals("pptx") && !extension.equals("ppt") && !extension.equals("pdf")
                && !extension.equals("png") && !extension.equals("jpg") && !extension.equals("jpeg")
                && !extension.equals("xls") && !extension.equals("xlsx") && !extension.equals("doc")
                && !extension.equals("docx")) {
            MToast.showToast(this, "上传附件格式不正确！");
            return;
        }

        if (checkFileSize(filePath)) {
            mBinding.tvUploadAnnex.setVisibility(View.GONE);
            mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);

            long fileLength = FileUtil.getFileLength(filePath);
            fileSize = FileUtil.formatFileSize(fileLength);
            fileType = FileUtil.getMimeType(new File(filePath));
            mBinding.tvAnnexName.setText(fileName);
            mBinding.tvAnnexSize.setText(fileSize);
            switch (fileType) {
                case "image/jpg":
                case "image/png":
                case "image/jpeg":
                    Glide.with(this).load(R.mipmap.merchant_icon_img_type).into(mBinding.ivAnnexSimple);
                    break;
                case "application/msword":
                case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                    Glide.with(this).load(R.mipmap.merchant_icon_doc).into(mBinding.ivAnnexSimple);
                    break;
                case "application/vnd.ms-powerpoint":
                case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                    Glide.with(this).load(R.mipmap.merchant_icon_ppt).into(mBinding.ivAnnexSimple);
                    break;
                case "application/vnd.ms-excel":
                case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                    Glide.with(this).load(R.mipmap.merchant_icon_xlsx).into(mBinding.ivAnnexSimple);
                    break;
                case "application/pdf":
                    Glide.with(this).load(R.mipmap.merchant_icon_pdf).into(mBinding.ivAnnexSimple);
                    break;
            }
        }
        LogUtil.d("TAG", "handleFileChoose filePath:" + filePath);
    }

    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private boolean checkFileSize(String filePath) {
        float sizeCount = 0f;
        long fileLength = FileUtil.getFileLength(filePath);
        String fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB);
        if (fileSize.contains("MB")) {
            String fileSizeCount = fileSize.replace("MB", "");
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = Float.parseFloat(fileSizeCount);
                if (sizeCount > 10) {
                    MToast.showToast(this, "上传文件大小不能超过10MB!");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取地址
     */
    public static AMapAddressEntity get(Intent data) {
        if (data == null) {
            return null;
        }
        return data.getParcelableExtra(RouterKey.DATA);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getEditContent();
            if (hasContent) {
                showHintDialog();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
